package com.xiaoge.iocbeanlifecle;

import com.xiaoge.service.OrderService;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.annotation.ScannedGenericBeanDefinition;
import org.springframework.stereotype.Component;

import static org.springframework.beans.factory.support.AbstractBeanDefinition.AUTOWIRE_BY_NAME;

/**
 * TODO
 *
 * @author <a href="mailto:1330137071@qq.com">Zhang Xiao</a>
 * @since
 */
@Component
public class MyBeanFactoryPostProcessor implements BeanDefinitionRegistryPostProcessor {

	/**
	 * 主要是用来修改Bean定义
	 * @param beanFactory the bean factory used by the application context
	 * @throws BeansException
	 */
	@Override
	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
		// todo 获取bean定义  (因为通过@ComponentScan, 扫描出来的BeanDefinition都是ScannedGenericBeanDefinition)
		ScannedGenericBeanDefinition userService = (ScannedGenericBeanDefinition)beanFactory.getBeanDefinition("userService");

		// 设置多例bean
		// userService.setScope("prototype");

		// 设置懒加载
		// userService.setLazyInit(true);

		// 修改Class
		// userService.setBeanClass(OrderService.class)
		// 设置默认值 相当于 xml: <property name="name" value="张啸" />
		// userService.getPropertyValues().addPropertyValue(new PropertyValue("name", "张啸"));

		// 设置构造函数 相当于xml: <constructor-arg index="0" value"张啸" />
		// userService.getConstructorArgumentValues().addIndexedArgumentValue(0, "张啸");

		// 自动装配方式
		userService.setAutowireMode(AUTOWIRE_BY_NAME);
		// 强制依赖检查
		// userService.setDependencyCheck(DEPENDENCY_CHECK_ALL);

		// 设置bean初始化方法名称
		// userService.setInitMethodName("initMethod");
	}


	/**
	 * 主要是用来注册bean定义
	 * @param registry the bean definition registry used by the application context
	 * @throws BeansException
	 */
	@Override
	public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
		RootBeanDefinition rootBeanDefinition = new RootBeanDefinition();
		rootBeanDefinition.setBeanClass(OrderService.class);
		registry.registerBeanDefinition("userService", rootBeanDefinition);
	}
}
